﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Data;
using System.IO;
using System.Web;
using System.Threading;

namespace KenLib.Common
{
    public class ExportFile
    {
        /// <summary>
        /// トアイン
        /// 2010/05/24
        ///	CVS出力する
        /// </summary>
        /// <param name="strPath"></param>
        /// <param name="dt"></param>
        /// <param name="strHeader"></param>
        /// <param name="strColumnNamesRemove"></param>
        /// <returns></returns>
        public static bool ExportCSV(string strFileName, DataTable dt, string strHeader, string strColumnsCancel,string strColumnImage)
        {
            try
            {
                strColumnsCancel = strColumnsCancel.ToLower();
                strFileName = HttpUtility.UrlEncode(strFileName, Encoding.GetEncoding("utf-8"));
                HttpBrowserCapabilities browse = HttpContext.Current.Request.Browser;
                string attachment = string.Format("attachment; filename={0}.csv", browse.Browser.ToLower() == "firefox" ? HttpUtility.UrlDecode(strFileName) : strFileName);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.ClearContent();

                HttpContext.Current.Response.AddHeader("content-disposition", attachment);
                HttpContext.Current.Response.ContentType = "text/csv";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("shift-jis");

                HttpContext.Current.Response.Write(strHeader);
                HttpContext.Current.Response.Write(Environment.NewLine);
                foreach (DataRow r in dt.Rows)
                {
                    string strTemp = "";
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        //if (strColumnsCancel.IndexOf(string.Format("{0} ,", dt.Columns[i].ColumnName.ToLower())) == -1 && strColumnImage.ToLower().IndexOf(string.Format("{0} ,", dt.Columns[i].ColumnName.ToLower()).Replace(" ", "")) == -1)//sua 20101124
                        if (strColumnsCancel.IndexOf(string.Format("{0} ,", dt.Columns[i].ColumnName.ToLower())) == -1 )
                        {
                            strTemp += "\"";
                            strTemp += (i + 1 == dt.Columns.Count ? r[i].ToString() + "\"" : string.Format("{0}\",", r[i].ToString()));
                        }
                    }
                    if (strTemp != "")
                    {
                        HttpContext.Current.Response.Write(strTemp.Trim());
                        HttpContext.Current.Response.Write(Environment.NewLine);
                    }
                }
                HttpContext.Current.Response.End();
            }
            catch (ThreadAbortException err)
            {
                return false;
            }
            catch (Exception err)
            {
                return true;
            }
            return true;
        }
       
        /// <summary>
        /// トアイン
        /// 2010/05/24
        ///	ログファイルを記載する。
        /// </summary>
        /// <param name="user"></param>
        /// <param name="table"></param>
        /// <param name="active"></param>
        public static void WriteLog(string user, string table, string active, string content, string RequestTime, string DisplayTime)
        {
            //string directoryString = HttpContext.Current.Server.MapPath("LOG");
            //if (!Directory.Exists(directoryString))
            //{
            //    Directory.CreateDirectory(directoryString);
            //}
            //string FILENAME = HttpContext.Current.Server.MapPath("LOG/"+DateTime.Now.ToString("yyyyMMdd") +  ".log.csv");
            //bool isExist=File.Exists(FILENAME);
            // FileStream l_FileStream = new FileStream(FILENAME, FileMode.Append, FileAccess.Write);
            // StreamWriter objStreamWriter = new StreamWriter(l_FileStream, Encoding.GetEncoding("shift-jis"));
            //if (!isExist)
            //    objStreamWriter.WriteLine("時間 ,担当者 ,テーブル名 ,機能 ,内容 ,RequestTime ,DisplayTime");
            //objStreamWriter.WriteLine(string.Format("{0} ,{1} ,{2} ,{3} ,{4} ,{5} ,{6}", DateTime.Now.ToString(), user, table, active, content, RequestTime, DisplayTime));
            //objStreamWriter.Close();
        }

        /// <summary>
        /// トアイン
        /// 2010/05/24
        ///	エラーファイルを記載する。。 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="err"></param>
        public static void WriteErr(string user, string table, string active, string content, string RequestTime, string DisplayTime)
        {
            //string directoryString = HttpContext.Current.Server.MapPath("ERROR");
            //if (!Directory.Exists(directoryString))
            //{
            //    Directory.CreateDirectory(directoryString);
            //}
            //string FILENAME = HttpContext.Current.Server.MapPath("ERROR/" + DateTime.Now.ToString("yyyyMMdd") + ".err.csv");
            //bool isExist = File.Exists(FILENAME);
            //FileStream l_FileStream = new FileStream(FILENAME, FileMode.Append, FileAccess.Write);
            //StreamWriter objStreamWriter = new StreamWriter(l_FileStream, Encoding.GetEncoding("shift-jis"));
            //if (!isExist)
            //    objStreamWriter.WriteLine("時間 ,担当者 ,テーブル名 ,機能 ,内容 ,RequestTime ,DisplayTime");
            //objStreamWriter.WriteLine(string.Format("{0} ,{1} ,{2} ,{3} ,{4} ,{5} ,{6}", DateTime.Now.ToString(), user, table, active, content, RequestTime, DisplayTime));
            //objStreamWriter.Close();
        }

    }

}
